package com.qf.util;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 2019/11/25
 * 键盘敲烂，月薪过万
 * 登高必自卑，行远必自迩。
 * 不忘初心：像初学者一样拥有一颗谦虚、开放的心态。
 * 李学峰
 */
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //判断是否是匿名地址（公开地址）
        String requestURI = request.getRequestURI();
        ResourceBundle anon = ResourceBundle.getBundle("anon");
        if (anon.containsKey(requestURI)){
            //属于匿名地址
            return true;
        }

        //是否是公共地址
        ResourceBundle publicUri = ResourceBundle.getBundle("public");
            if (publicUri.containsKey(requestURI)){
                return true;
            }

        //判断请求是否属于当前登录的用户
        Employee user = (Employee)request.getSession().getAttribute("user");
        List<Menu> menuList = user.getRole().getMenus();
        for (Menu menu : menuList) {
            if (requestURI.equals(menu.getUrl())){
                return  true;
            }else {
                List<Menu> secondMenu = menu.getSecondMenu();
                for (Menu secondMenu1 : secondMenu) {
                    if (requestURI.equals(secondMenu1.getUrl())){
                        return true;
                    }
                }
            }
        }
        List<Menu> list = user.getRole().getPermissionList();
        for (Menu menu : list) {
            if (requestURI.equals(menu.getUrl())){
                return true;
            }
        }


        //授权失败
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<script>location.href='/error.jsp'</script>");
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
